# -*- coding: utf-8 -*-

'''eof
name:申请企业未结清保理等业务五级分类校验
code:Ent_UnpaidFactorEtc_Class5StateCheck
tableName:
columnName:
groups:准入>企业征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:申请企业未结清保理等业务五级分类校验
eof'''

'''
ECRSummaryUnsettled02（未结清信贷信息概要（7类信贷业务）） list
用业务类型匹配: 贸易融资、保理、银行承兑汇票、信用证、保函、类贷款
再分别统计加总 关注 不良 的汇总笔数
最后返回总个数
Concernedsum_Number	关注类汇总（笔数）
LoanType	业务类型
Badsum_Number	不良类汇总（笔数）

'''
import sys
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
import json

reload(sys)
sys.setdefaultencoding('utf-8')

#如果这个字段存在 但是里面的list长度为0 不包含任何dict 应该返回缺失值 不应该为0
def FormatData(tableName):
    try:
        ecr = json.loads(EC[0]["ecr"])[tableName]
        return ecr if isinstance(ecr, list) and len(ecr) > 0 else [{}]
    except:
        return [{}]

def Ent_UnpaidFactorEtc_Class5StateCheck():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    loan_type = ['贸易融资','保理','银行承兑汇票','信用证','保函','类贷款']
    count = []
    try:
        ECRSummaryUnsettled02 = FormatData('ECRSummaryUnsettled02')

        if ECRSummaryUnsettled02 == [{}]:
            return u'缺失值'
        else:
            if len(ECRSummaryUnsettled02) >=1:
                for i in ECRSummaryUnsettled02:
                    if i.has_key('LoanType') :
                        if i['LoanType'].strip() in loan_type:
                            #对关注类汇总（笔数）计数
                            if i.has_key('Concernedsum_Number') and isfloat(i['Concernedsum_Number']):
                                count.append(float(i['Concernedsum_Number']))
                            else:
                                count.append(None)
                            #对不良类汇总（笔数）计数
                            if i.has_key('Badsum_Number') and isfloat(i['Badsum_Number']):
                                count.append(float(i['Badsum_Number']))
                            else:
                                count.append(None)
                    else:
                        count.append(None)
                if None in set(count) and len(set(count)) == 1:
                    return u'缺失值'
                else:
                    count_notnone = [i for i in count if i!=None]
                    return sum(count_notnone)
            
            else:
                return u'缺失值'
    except:
        return u'缺失值'
    
    
def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False

result = Ent_UnpaidFactorEtc_Class5StateCheck()